<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Download, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import { BillingService, type ReceivableData, type BillingQueryParams } from '@/services/billingService';

/**
 * 此页面对应账单中心的 应收单管理
 */
// 查询条件
const queryForm = reactive({
  cargoNo: '', // 货号
  waybillNo: '', // 运单号
  customer: '', // 客户
  orderStatus: '', // 订单状态
  settlementStatus: '', // 结算状态
  reconciliationStatus: '', // 对账单状态
  startDate: '', // 开始日期
  endDate: '', // 结束日期
  shippingStation: '', // 发货站
  deliveryStation: '' // 到达站
});

// 表格数据
const tableData = ref<ReceivableData[]>([]);
// 表格加载状态
const loading = ref(false);
// 表格选中的行
const selectedRows = ref<ReceivableData[]>([]);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 状态选项
const orderStatusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' }
];

const settlementStatusOptions = [
  { value: 'unsettled', label: '未结算' },
  { value: 'settled', label: '已结算' }
];

const reconciliationStatusOptions = [
  { value: 'unreconciled', label: '未对账' },
  { value: 'reconciled', label: '已对账' }
];

// 站点选项
const stationOptions = [
  { value: 'shijiazhuang', label: '石家庄站' },
  { value: 'beijing', label: '北京站' },
  { value: 'tianjin', label: '天津站' },
  { value: 'shanghai', label: '上海站' },
  { value: 'guangzhou', label: '广州站' },
  { value: 'shenzhen', label: '深圳站' }
];

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    const params: BillingQueryParams = {
      cargoNo: queryForm.cargoNo,
      orderNo: queryForm.waybillNo,
      customer: queryForm.customer,
      orderStatus: queryForm.orderStatus ? parseInt(queryForm.orderStatus) : undefined,
      settlementStatus: queryForm.settlementStatus ? parseInt(queryForm.settlementStatus) : undefined,
      reconciliationStatus: queryForm.reconciliationStatus ? parseInt(queryForm.reconciliationStatus) : undefined,
      startDate: queryForm.startDate,
      endDate: queryForm.endDate,
      shippingStation: queryForm.shippingStation,
      deliveryStation: queryForm.deliveryStation,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    const result = await BillingService.getReceivableList(params);
    
    if (result.success) {
      tableData.value = result.data;
      pagination.total = result.total;
    } else {
      ElMessage.error('获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQueryForm = () => {
  Object.keys(queryForm).forEach(key => {
    (queryForm as any)[key] = '';
  });
  handleSearch();
};

// 查询数据
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTableData();
};

// 处理表格选择变化
const handleSelectionChange = (rows: ReceivableData[]) => {
  selectedRows.value = rows;
};

// 处理分页变化
const handlePageChange = (currentPage: number) => {
  pagination.currentPage = currentPage;
  fetchTableData();
};

// 处理每页条数变化
const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.currentPage = 1;
  fetchTableData();
};

// 生成对账单
const generateReconciliation = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要生成对账单的记录');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要为选中的${selectedRows.value.length}条记录生成对账单吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const receivableIds = selectedRows.value.map(row => row.objectId!);
    const customerName = selectedRows.value[0]?.customerName || selectedRows.value[0]?.senderName || '未知客户';
    
    const result = await BillingService.generateReconciliation(receivableIds, {
      customerName,
      creator: '当前用户' // 这里应该从用户状态获取
    });
    
    if (result.success) {
      ElMessage.success('对账单生成成功');
      fetchTableData();
    } else {
      ElMessage.error('对账单生成失败');
    }
  } catch (error) {
    // 用户取消操作或其他错误
  }
};

// 结算
const handleSettle = async (row: ReceivableData) => {
  try {
    await ElMessageBox.confirm(
      `确定要结算运单号为${row.orderNo}的记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await BillingService.settleReceivable(row.objectId!);
    
    if (result.success) {
      ElMessage.success('结算成功');
      fetchTableData();
    } else {
      ElMessage.error('结算失败');
    }
  } catch (error) {
    // 用户取消操作或其他错误
  }
};

// 生成单个对账单
const handleGenerateReconciliation = async (row: ReceivableData) => {
  try {
    await ElMessageBox.confirm(
      `确定要为运单号${row.orderNo}生成对账单吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await BillingService.generateReconciliation([row.objectId!], {
      customerName: row.customerName || row.senderName,
      creator: '当前用户' // 这里应该从用户状态获取
    });
    
    if (result.success) {
      ElMessage.success('对账单生成成功');
      fetchTableData();
    } else {
      ElMessage.error('对账单生成失败');
    }
  } catch (error) {
    // 用户取消操作或其他错误
  }
};

// 格式化日期
const formatDate = (date: Date | string): string => {
  if (!date) return '';
  const d = new Date(date);
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchTableData();
});
</script>

<template>
  <div class="billing-receivable-view">
    <div class="page-header">
      <h2 class="page-title">应收单管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryForm">
        <!-- 第一行：客户、订单状态、发货站、到达站 -->
        <div class="search-row first-row">
          <div class="form-group">
            <el-form-item label="客户">
              <el-input v-model="queryForm.customer" placeholder="请输入客户名称" clearable></el-input>
            </el-form-item>
          </div>
          
          <div class="form-group">
            <el-form-item label="订单状态">
              <el-select v-model="queryForm.orderStatus" placeholder="请选择" clearable>
                <el-option
                  v-for="item in orderStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-group">
            <el-form-item label="发货站">
              <el-select v-model="queryForm.shippingStation" placeholder="请选择" clearable>
                <el-option
                  v-for="item in stationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-group">
            <el-form-item label="到达站">
              <el-select v-model="queryForm.deliveryStation" placeholder="请选择" clearable>
                <el-option
                  v-for="item in stationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        
        <!-- 第二行：日期和按钮 -->
        <div class="search-row second-row">
          <div class="date-group">
            <div class="form-group">
              <el-form-item label="开始日期">
                <el-date-picker
                  v-model="queryForm.startDate"
                  type="date"
                  placeholder="选择开始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                ></el-date-picker>
              </el-form-item>
            </div>
            
            <div class="form-group">
              <el-form-item label="结束日期">
                <el-date-picker
                  v-model="queryForm.endDate"
                  type="date"
                  placeholder="选择结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                ></el-date-picker>
              </el-form-item>
            </div>
          </div>
          
          <div class="button-group">
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button @click="resetQueryForm">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left">
        <el-button type="primary" :icon="Plus" @click="generateReconciliation">生成对账单</el-button>
        <el-button :icon="Download">导出</el-button>
        <el-button :icon="Refresh" @click="fetchTableData">刷新</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column prop="cargoNo" label="货号" width="120" fixed="left" />
      <el-table-column prop="orderNo" label="运单号" width="120" fixed="left" />
      <el-table-column prop="customerName" label="客户" width="100" />
      <el-table-column prop="orderStatus" label="订单状态" width="100">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.orderStatus === 0 ? 'warning' :
              scope.row.orderStatus === 1 ? 'primary' :
              scope.row.orderStatus === 2 ? 'success' : 'danger'
            "
            size="small"
          >
            {{ BillingService.getOrderStatusText(scope.row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="senderAddress" label="发货地址" width="180" show-overflow-tooltip />
      <el-table-column prop="receiverAddress" label="收货地址" width="180" show-overflow-tooltip />
      <el-table-column prop="settlementStatus" label="结算状态" width="100">
        <template #default="scope">
          <el-tag
            :type="scope.row.settlementStatus === 0 ? 'danger' : 'success'"
            size="small"
          >
            {{ BillingService.getSettlementStatusText(scope.row.settlementStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="settlementTime" label="结算时间" width="160">
        <template #default="scope">
          {{ scope.row.settlementTime ? formatDate(scope.row.settlementTime) : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="reconciliationStatus" label="对账单状态" width="100">
        <template #default="scope">
          <el-tag
            :type="scope.row.reconciliationStatus === 0 ? 'danger' : 'success'"
            size="small"
          >
            {{ BillingService.getReconciliationStatusText(scope.row.reconciliationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reconciliationNo" label="对账单号" width="120" />
      <el-table-column prop="totalFreight" label="运费合计" width="120">
        <template #default="scope">
          <span>￥{{ scope.row.totalFreight }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="deliveryFee" label="配送费" width="120">
        <template #default="scope">
          <span>￥{{ scope.row.deliveryFee }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unloadingFee" label="卸货费" width="120">
        <template #default="scope">
          <span>￥{{ scope.row.unloadingFee }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            text
            @click="handleSettle(scope.row)"
            v-if="scope.row.settlementStatus === 0"
          >
            结算
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            text
            @click="handleGenerateReconciliation(scope.row)"
            v-if="scope.row.reconciliationStatus === 0 && scope.row.settlementStatus === 1"
          >
            生成对账单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.billing-receivable-view {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.search-container {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.search-row {
  display: flex;
  margin-bottom: 16px;
}

.search-row.first-row {
  justify-content: space-between;
  flex-wrap: nowrap;
}

.search-row.second-row {
  justify-content: flex-start;
  margin-bottom: 0;
}

.form-group {
  margin-right: 12px;
  margin-bottom: 0;
}

.first-row .form-group {
  flex: 1;
  min-width: 0;
}

.form-group:last-child {
  margin-right: 0;
}

/* 让每个表单项内部更紧凑 */
.form-group :deep(.el-form-item) {
  margin-bottom: 0;
}

.form-group :deep(.el-form-item__label) {
  padding-right: 6px;
}

.form-group :deep(.el-form-item__content) {
  min-width: 150px;
}

.date-group {
  display: flex;
  margin-right: 20px;
}

.button-group {
  display: flex;
  align-items: flex-end;
}

.button-group .el-button {
  margin-right: 10px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 